<?php


namespace app\api\controller;


use app\admin\model\BetOrder;
use app\admin\model\DataPrice;
use app\admin\model\Member;
use app\admin\model\SysConfig;
use app\admin\model\TransactionHistory;
use app\common\CacheKey;
use app\common\Status;
use think\Db;

class Market extends Base
{

    public function order()
    {
        //检查参数
        $post = $this->request->post();
        $this->check($post, 'app\api\validate\UserValidate.order');
        list($money, $betType, $marketType, $dealTime, $assetsType) = [$post['money'], $post['betType'], $post['marketType'], $post['dealTime'], $post['assetsType']];

        $orderLock = getSystemConfig('ORDER_LOCK');
        if (!$orderLock) {
            //竞猜开关
            return returnJson(Status::FAILED, lang('order_lock'));
        }

        //周末禁止下单
        if (time() >= strtotime('Saturday')) {
            return returnJson(Status::FAILED, lang('time_error'));
        };

        //1.检查金额是否在配置的范围内，
        $maxMoney = SysConfig::getInstance()->getValues(['name' => 'ORDER_MONEY_MAX']);
        $minMoney = SysConfig::getInstance()->getValues(['name' => 'ORDER_MONEY_MIN']);
        if ($money > $maxMoney || $money < $minMoney) {
            return returnJson(Status::FAILED, lang('money_err').":$minMoney ~ $maxMoney");
        }

        $payRes       = true;
        $serviceMoney = bcdiv(getSystemConfig('BET_SERVICE_MONEY'), 100, 2);//0.2
        $earnRate     = getSystemConfig('BET_EARN_RATE');

        try {
            Db::startTrans();
            //判断是否够钱，够钱的话则扣钱，增加扣钱流水，生成一笔竞猜订单.
            if ($assetsType == 1) {
                //uf支付，生产uf流水，扣uf钱
                $pid = \app\api\service\Market::ufPay($this->uid, $money);
            } else {
                //体验金
                $pid = \app\api\service\Market::expPay($this->uid, $money);
            }

            //不是数字，而且是一个字符串的时候
            if (!is_numeric($pid) && is_string($pid)) {
                Db::rollback();
                return returnJson(Status::FAILED, lang($pid));
            }

            //生成订单
            $price_start_time = date("Y-m-d H:i:00", strtotime("+1 minute"));
            $price_end_time   = date("Y-m-d H:i:00", strtotime("+2 minute"));
            $time = time();
            if (($time + 60) == strtotime($price_start_time)) {
                //刚好整点下单
                $price_start_time = date('Y-m-d H:i:00',$time);
                $price_end_time   = date('Y-m-d H:i:00', ($time + 60));
            }
            $order = [
                'uid'              => $this->uid,
                'money'            => $money,
                'market_type'      => $marketType,
                'deal_time'        => $dealTime,
                'assets_type'      => $assetsType,
                'user_bet_type'    => $betType,
                'number'           => createOrderNumber(),
                'earn_rate'        => $earnRate,
                'service_money'    => $serviceMoney,
                'price_start_time' => $price_start_time,
                'price_end_time'   => $price_end_time,
            ];
            BetOrder::getInstance()->insert($order);

            //然后在封装一个升级方法，给上级升级，升级完。自己在购买时是有可能升级的，所以传入当前用户id
            //\app\api\service\Market::upgradeLevel($this->uid,$money,$this->uid);
            Db::commit();

            //将奖金扔到队列中，异步发放奖金。自己在购买时是给上级分佣的，所以传入父id
            //redis()->lPush(CacheKey::BET_BONUS, json_encode(['uid' => $pid]));
            return returnJson(Status::SUCCESS, lang('order_success'));
        } catch (\Exception $e) {
            Db::rollback();
            errorLog($this->action, $e);
            return returnJson(Status::SYSTEM_ERROR, lang('system_error'));
        }
    }

    /**
     * Notes: 明细记录
     * User: allen
     * DateTime: 2021/11/4 下午4:23
     * @return \think\response\Json
     */
    public function getBetDetail()
    {
        $params = $this->request->get();
        $this->check($params,'app\api\validate\UserValidate.paginate');

        try {
            //查流水记录
            $field = 'number,status,money,create_time,user_bet_type,service_money,earn_rate,assets_type,price_start,price_end';
            $data = BetOrder::getInstance()->getPage(['uid' => $this->uid],$params['page'],$params['size'],'id desc ',$field);
            if (!$data) {
                //空数据
                return returnJson(Status::SUCCESS, lang('success'));
            }
            foreach ($data['data'] as $k => &$v) {
                $unit = $v['assets_type'] == 1 ? 'UF' : '';//1uf,其他则体验金
                $v['money'] = \app\api\service\Market::getBetRes($v) . ' ' . $unit;
                unset($v['service_money']);
                unset($v['earn_rate']);
            }
            return returnJson(Status::SUCCESS, lang('success'),$data['data']);
        } catch (\Exception $e) {
            errorLog($this->action, $e);
            return returnJson(Status::SYSTEM_ERROR, lang('system_error'));
        }
    }

    /**
     * Notes:获取k线数据
     * User: allen
     * DateTime: 2021/11/4 下午6:23
     * @return \think\response\Json
     */
    public function geBrokenLine()
    {
        //行情品种，
        $params = $this->request->get();
        $this->check($params,'app\api\validate\UserValidate.geBrokenLine');

        $num = 10;
        if (isset($params['num']) && is_numeric($params['num']) && $params['num'] > 0) {
            $num =  $params['num'];
        }
        list($market, $time) = [strtoupper($params['market']),strtolower($params['time'])];
        //根据market和time去查询对应的数据 GC 黄金  SI 白银  CL 原油  HG 铜
        $type = ['1' => 'GC','2' => 'SI','3' => 'CL','4' => 'HG'];
        $timeType = ['m' => 0,'h' => '1','d' => 2, '15m' => '3', '30m' => '4'];
        try {
            //查最新的前10条数据
            $data = DataPrice::getInstance()->getMany(['data_type' => $type[$market],'type' => $timeType[$time]],'data_type as market,time,start_price,end_price,hight_price,low_price,type',$num,false,'time desc');
            return returnJson(Status::SUCCESS, lang('success'),$data);
        } catch (\Exception $e) {
            errorLog($this->action, $e);
            return returnJson(Status::SYSTEM_ERROR, lang('system_error'));
        }
    }


}
